package swu.cart;

import swu.commodity.Commodity;
import swu.commodity.CommodityRepo;
import swu.commodity.CommodityService;
import swu.core.ObjectRepo;
import swu.core.ResultSetIterator;
import swu.user.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CartRepo extends CommodityRepo
{
    private Commodity getOneCommodity(ResultSet resultSet) throws SQLException
    {
        Commodity commodity = new Commodity();

        commodity.setId(resultSet.getInt("id"));
        commodity.setName(resultSet.getString("name"));
        commodity.setOrigin(resultSet.getString("origin"));
        commodity.setPrice(resultSet.getDouble("price"));
        commodity.setCategory(resultSet.getString("category"));
        commodity.setProductionDate(resultSet.getDate("productionDate"));
        commodity.setImage(resultSet.getString("image"));

        return commodity;
    }

    public List<Commodity> getAllFromCart(String username) throws SQLException
    {
        List<Commodity> commodities = new ArrayList<>();
        String sql = "select * from " + username + "_cart";

        this.queryAll(sql, new ResultSetIterator() {
            @Override
            public void visit(ResultSet rs) throws SQLException
            {
                commodities.add(getOneCommodity(rs));
            }
        });

        return  commodities;
    }

    public void addToCartById(List<Commodity> cart, int id) throws SQLException
    {
        Commodity commodity = this.getById(id);
        cart.add(commodity);
    }

    public void deleteFromCartById(List<Commodity> cart, int id) throws SQLException
    {
        Iterator<Commodity> iterator = cart.iterator();

        while (iterator.hasNext())
        {
            Commodity commodity = iterator.next();
            if(commodity.getId() == id)
            {
                iterator.remove();
                return;
            }
        }
    }

    public Boolean isCommodityExists(List<Commodity> cart,int id) throws SQLException
    {
        for(Commodity commodityItem:cart)
        {
            if(commodityItem.getId() == id)
            {
                return true;
            }
        }

        return false;
    }
}
